package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.service.MemberService;
import com.atguigu.service.ReportService;
import com.atguigu.service.SetmealService;
import org.apache.poi.hpsf.ReadingNotSupportedException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ReportController
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-19
 * @Description:
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private ReportService reportService;

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            //远程调用报表服务获取报表数据
            Map<String, Object> result = reportService.getBusinessReportData();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            // 把数据 写到excel表格里面 "/"
            //获得Excel模板文件绝对路径
            //file.separator这个代表系统目录中的间隔符，说白了就是斜线，不过有时候需要双线，有时候是单线，你用这个静态变量就解决兼容问题了。
            // "template/report_template.xlsx"
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "report_template.xlsx";
            // 获取excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
            // 获取页签对象
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            // 写行数据
            XSSFRow row = sheetAt.getRow(2);
            // 写列数据
            row.getCell(5).setCellValue(reportDate);

            row = sheetAt.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            row = sheetAt.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            ServletOutputStream out = response.getOutputStream();
            // 设置数据类型 "application/json"
            // 下载的数据类型（excel类型） mime
            response.setContentType("application/vnd.ms-excel");
            // 设置下载形式(通过附件的形式下载)
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();
            return  null;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;

    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
       Map<String,Object> map =  reportService.getBusinessReportData();
       return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
    }


    /**
     * 需求：通过饼形图直观的展示出会员预约的各个套餐占比情况
     *  setmealNames: ['澳门威尼斯人商圈酒店双飞3-5日自由行套餐', '香港九龙尖沙咀商圈双飞3-8日自由行套餐', '联盟广告', '视频广告', '搜索引擎']
     *  setmealCount: [
     {value: 335, name: '澳门威尼斯人商圈酒店双飞3-5日自由行套餐'},
     {value: 310, name: '香港九龙尖沙咀商圈双飞3-8日自由行套'},
     {value: 234, name: '联盟广告'},
     {value: 135, name: '视频广告'},
     {value: 1548, name: '搜索引擎'}
     ],
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
       List<Map<String,Object>> lists =  setmealService.findSetmealCount();
       Map<String, Object> map = new HashMap<>();
       List<Object> setmealNames = new ArrayList<>();
        for (Map<String, Object> list : lists) {
           String name = (String) list.get("name");
            setmealNames.add(name);
        }
       map.put("setmealCount",lists);
       map.put("setmealNames",setmealNames);
       return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);

    }


    /**
     * data:{
     *      months: ["2020-03","2020-04","2020-05","2020-06","2020-07","2020-08"]
     *      memberCount:[5, 20, 36, 10, 10, 20]
     *       }
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        //需求：展示过去一年(12个月)每个月，会员注册的数量
        // 创建日历对象
        Calendar calendar = Calendar.getInstance();
        // 需要倒退到过去12个月
        // 第一个参数；表示属性(月份)2020-03
        // 第二个参数：表示往前面推12 个月
        calendar.add(Calendar.MONTH,-12);
        // 存放月份
        List<String> lists = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            // 一个月一个月的添加
            calendar.add(Calendar.MONTH,1);

            // 把过去的12个月的月份，全部添加到集合里面
            lists.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()) );
        }
        // 查询会员数量
        List<Integer> memberCount =   memberService.findMemberCountByMonth(lists);

        Map<String, Object> map = new HashMap<>();
        map.put("months",lists);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
}